import MSData
import WorkerMSAPI
import WorkerMSDB
import MSConfig
import MSLogger

import BaseHTTPServer
import time
import os
import sys
import pdb

MSLogger.logInit('D:\work\ms.log', 5, True)
reader      = WorkerMSAPI.Worker()
mobile_groups = MSConfig.readObjectsConfig('mobile_objects.cfg')

#p - page
def writeBegin(p):
    p.write('\
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\
        <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">\
          <head>\
            <meta http-equiv="content-type" content="text/html; charset=utf-8"/>\
            <title>Google Maps JavaScript API Example: Simple Icon</title>\
            <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAqOj1h9QN91TQBa2M4tBMcxT2yXp_ZAY8_ufC3CFXhHIE1NvwkxRc2tmSQwmGIxTGxtZIgE5dBXq5vw"\
                    type="text/javascript"></script>\
            <script type="text/javascript">\
    ')

def writeMobileGroup(p, mobile_groups):
    #blueIcon.image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/blue/blank.png";\
    p.write('\
            function mapMobileGroups(map) {\
                var blueIcon = new GIcon(G_DEFAULT_ICON);\
                blueIcon.iconSize = new GSize(45,30);\
                blueIcon.image = "http://extras.inyork.com/redesign2010/images/autoIcon.png";\
                markerOptions = { icon:blueIcon };\
    ')
    for o in mobile_groups:
        if not o.eventsGPS: continue
        if len(o.eventsGPS) == 0: continue
        last = o.eventsGPS[len(o.eventsGPS) - 1]
        p.write('map.addOverlay(new GMarker(new GLatLng(%s, %s), markerOptions));' % (last.GPSLatitudeOrig, last.GPSLongitudeOrig))

    p.write('\
            }\
    ')


def writeEnd(p):
    p.write('\
            function initialize() {\
              if (GBrowserIsCompatible()) {\
                var map = new GMap2(document.getElementById("map_canvas"));\
                map.setCenter(new GLatLng(59.986379, 30.248780), 8);\
                map.setUIToDefault();\
                mapMobileGroups(map);\
              }\
            }\
            </script>\
          </head>\
          <body onload="initialize()" onunload="GUnload()">\
            <div id="map_canvas" style="width: 1000px; height: 600px"></div>\
          </body>\
        </html>\
    ')


class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.end_headers()

        reader.readEventsGPS(mobile_groups)

        writeBegin(self.wfile)
        writeMobileGroup(self.wfile, mobile_groups)
        writeEnd(self.wfile)
        return


if __name__ == '__main__':
    from BaseHTTPServer import HTTPServer
    server = HTTPServer(('localhost', 8080), MyHandler)
#    MSLogger.logInfo('ms online checker started, <Ctrl-C> to stop')
    server.serve_forever()



